package com.glsc.ngateway.opmanage.controller.outsys;

import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.outsys.OutSystemAuthTemplate;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.outsys.OutSystemTemplateItem;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.outsys.OutSystemTemplateRel;
import com.glsc.ngateway.opmanage.dto.OutSystemQueryDto;
import com.glsc.ngateway.opmanage.service.outsys.OutSystemAuthTemplateService;
import com.glsc.ngateway.opmanage.service.outsys.OutSystemTemplateItemService;
import com.glsc.ngateway.opmanage.service.outsys.OutSystemTemplateRelService;
import com.glsc.ngateway.opmanage.service.outsys.OutSystemTemplateService;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 外部系统权限模板-系统关联表
 */
@RestController
@RequestMapping("/api/outSystem/template/rel")
@Slf4j
public class OutSystemTemplateRelController {

    @Resource
    private OutSystemTemplateRelService relService;

    @Resource
    private OutSystemTemplateItemService itemService;

    @Resource
    private OutSystemAuthTemplateService authTemplateService;

    @Resource
    private OutSystemTemplateService templateService;

    @Resource
    private OutSystemTemplateItemService outSystemTemplateItemService;


    /**
     * 分页查询
     *
     * @param outSystemQueryDto
     * @return
     */
    @PostMapping("/page")
    public PlatformResponse<Page<OutSystemTemplateRel>> findClientPage(@RequestBody OutSystemQueryDto outSystemQueryDto) {
        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(outSystemQueryDto.getSystemName())) {
            param.put("LIKE_systemName", outSystemQueryDto.getSystemName());
        }

        Page<OutSystemTemplateRel> page = relService.page(PageUtil.initPageNo(outSystemQueryDto.getPageNo()), PageUtil.initPageSize(outSystemQueryDto.getPageSize()), param);
        return PlatformResponse.successData(page);
    }

    /**
     * 根据客户id查询客户信息
     *
     * @param
     * @return
     */
    @GetMapping("/findById")
    public PlatformResponse<OutSystemTemplateRel> findById(@ApiParam(value = "id") @RequestParam(required = true) Integer id) {
        OutSystemTemplateRel systemTemplateRel = relService.findSimpleInfoById(id);
        systemTemplateRel.setItems(Lists.newArrayList());
        systemTemplateRel.setCheckIdList(Lists.newArrayList());
        if (Objects.nonNull(systemTemplateRel)) {
            //systemTemplateRel.setOutSystemTemplate(templateService.findById(systemTemplateRel.getTemplateId()));
            List<OutSystemTemplateItem> outSystemTemplateItems = itemService.listByTemplateIdAndSysId(systemTemplateRel.getTemplateId(), systemTemplateRel.getSysId());
            if (CollectionUtils.isNotEmpty(outSystemTemplateItems)) {
                List<OutSystemAuthTemplate> authTempList = authTemplateService.findByIds(outSystemTemplateItems.stream().map(OutSystemTemplateItem::getAuthId).collect(Collectors.toList()));
                if (CollectionUtils.isNotEmpty(authTempList)) {
                    Map<Integer, OutSystemAuthTemplate> map = authTempList.stream().collect(Collectors.toMap(OutSystemAuthTemplate::getId, e -> e, (i, j) -> j));
                    List<Integer> checkIdList = Lists.newArrayList();
                    for (OutSystemTemplateItem outSystemTemplateItem : outSystemTemplateItems) {
                        OutSystemAuthTemplate outSystemAuthTemplate = map.get(outSystemTemplateItem.getAuthId());
                        if (Objects.nonNull(outSystemAuthTemplate)) {
                            outSystemTemplateItem.setAuthName1(outSystemAuthTemplate.getAuthName1());
                            outSystemTemplateItem.setAuthName2(outSystemAuthTemplate.getAuthName2());
                            outSystemTemplateItem.setAuthName3(outSystemAuthTemplate.getAuthName3());
                            outSystemTemplateItem.setAuthName4(outSystemAuthTemplate.getAuthName4());
                            outSystemTemplateItem.setAuthName5(outSystemAuthTemplate.getAuthName5());
                        }
                        if ("Y".equals(outSystemTemplateItem.getStatus())) {
                            checkIdList.add(outSystemTemplateItem.getId());
                        }
                    }
                    systemTemplateRel.setCheckIdList(checkIdList);
                }
            }
            systemTemplateRel.setItems(outSystemTemplateItems);
        }
        return PlatformResponse.successData(systemTemplateRel);
    }

    /**
     * 查看权限配置详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public PlatformResponse<OutSystemTemplateRel> detail(@ApiParam(value = "id") @RequestParam(required = true) Integer id) {
        OutSystemTemplateRel systemTemplateRel = relService.findSimpleInfoById(id);
        systemTemplateRel.setItems(Lists.newArrayList());
        systemTemplateRel.setCheckIdList(Lists.newArrayList());
        if (Objects.nonNull(systemTemplateRel)) {
            //systemTemplateRel.setOutSystemTemplate(templateService.findById(systemTemplateRel.getTemplateId()));
            List<OutSystemTemplateItem> outSystemTemplateItems = itemService.listByTemplateIdAndSysId(systemTemplateRel.getTemplateId(), systemTemplateRel.getSysId());
            outSystemTemplateItems = outSystemTemplateItems.stream().filter(e -> "Y".equals(e.getStatus())).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(outSystemTemplateItems)) {
                outSystemTemplateItems = Lists.newArrayList();
            }

            if (CollectionUtils.isNotEmpty(outSystemTemplateItems)) {
                List<OutSystemAuthTemplate> authTempList = authTemplateService.findByIds(outSystemTemplateItems.stream().map(OutSystemTemplateItem::getAuthId).collect(Collectors.toList()));
                if (CollectionUtils.isNotEmpty(authTempList)) {
                    Map<Integer, OutSystemAuthTemplate> map = authTempList.stream().collect(Collectors.toMap(OutSystemAuthTemplate::getId, e -> e, (i, j) -> j));
                    List<Integer> checkIdList = Lists.newArrayList();
                    for (OutSystemTemplateItem outSystemTemplateItem : outSystemTemplateItems) {
                        OutSystemAuthTemplate outSystemAuthTemplate = map.get(outSystemTemplateItem.getAuthId());
                        if (Objects.nonNull(outSystemAuthTemplate)) {
                            outSystemTemplateItem.setAuthName1(outSystemAuthTemplate.getAuthName1());
                            outSystemTemplateItem.setAuthName2(outSystemAuthTemplate.getAuthName2());
                            outSystemTemplateItem.setAuthName3(outSystemAuthTemplate.getAuthName3());
                            outSystemTemplateItem.setAuthName4(outSystemAuthTemplate.getAuthName4());
                            outSystemTemplateItem.setAuthName5(outSystemAuthTemplate.getAuthName5());
                        }
                        if ("Y".equals(outSystemTemplateItem.getStatus())) {
                            checkIdList.add(outSystemTemplateItem.getId());
                        }
                    }
                    systemTemplateRel.setCheckIdList(checkIdList);
                }
            }
            systemTemplateRel.setItems(outSystemTemplateItems);
        }
        return PlatformResponse.successData(systemTemplateRel);
    }


    /**
     * 保存
     *
     * @param outSystemAuthInfo
     * @return
     */
    @PostMapping("/save")
    public PlatformResponse<OutSystemTemplateRel> save(@RequestBody OutSystemTemplateRel outSystemAuthInfo) {
        List<OutSystemAuthTemplate> authList = Lists.newArrayList();
        if (Objects.isNull(outSystemAuthInfo.getId())) {
            //第一次创建系统关联信息,则查出这个系统关联的所有基准权限信息
            authList = authTemplateService.findBySystemId(outSystemAuthInfo.getSysId());
        }
        OutSystemTemplateRel rel = relService.save(outSystemAuthInfo);
        if (CollectionUtils.isNotEmpty(authList)) {
            List<OutSystemTemplateItem> addList = Lists.newArrayList();
            for (OutSystemAuthTemplate authTemplate : authList) {
                addList.add(OutSystemTemplateItem.builder().templateId(outSystemAuthInfo.getTemplateId()).sysId(outSystemAuthInfo.getSysId()).authId(authTemplate.getId())
                        .authName1(authTemplate.getAuthName1()).authName2(authTemplate.getAuthName2()).authName3(authTemplate.getAuthName3())
                        .authName4(authTemplate.getAuthName4()).authName5(authTemplate.getAuthName5())
                        .status("N").deleted("N").build());
            }

            if (CollectionUtils.isNotEmpty(addList)) {
                itemService.saveAll(addList);
            }
        }
        return PlatformResponse.successData(rel);
    }

    /**
     * 删除接口
     *
     * @return
     */
    @PostMapping("/delete")
    @Transactional
    public PlatformResponse<?> delete(@RequestBody OutSystemTemplateRel outSystemAuthInfo) {
        OutSystemTemplateRel systemTemplateRel = relService.findSimpleInfoById(outSystemAuthInfo.getId());
        outSystemTemplateItemService.deleteByTemplateIdAndSystemId(systemTemplateRel.getTemplateId(), systemTemplateRel.getSysId());
        relService.deleteById(outSystemAuthInfo.getId());
        return PlatformResponse.success();
    }


}
